﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net;
using System.Threading.Tasks;
namespace Odyssey.Http
{
    using Implementations;
    public static class HttpExtension
    {
        public static IServiceCollection AddOdysseyHttp(this IServiceCollection serviceCollection, Action<IHttpConfiguration> configurationAction = null)
        {
            var configuration = new HttpConfiguration()
            {
                DefaultClientName = "odyssey-http",
                DefaultTimeoutSeconds = 10,
                HttpResponseFilter = (httpResponseMessage) =>
                {
                    httpResponseMessage.EnsureSuccessStatusCode();
                    //if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
                    //{
                    //    throw new Exception($"HttpResponseMessage status code error:{httpResponseMessage.StatusCode.ToString()}");
                    //}
                    return Task.CompletedTask;
                }
            };
            configurationAction?.Invoke(configuration);
            serviceCollection.AddHttpClient();
            serviceCollection.AddSingleton<IHttpConfiguration>(configuration);
            serviceCollection.AddSingleton<IHttpSerializer, JsonHttpSerializer>();
            serviceCollection.AddSingleton<IHttpRequester, HttpRequester>();
            serviceCollection.AddSingleton<IPollyHttpRequester, PollyHttpRequest>();
            return serviceCollection;
        }
    }
}
